clear all
global system "linux"

if "${system}" == "linux" {
	*global code "/"
	global code "/"
	global s "/"
}

run "${code}${s}_set-path.do"


args index
cap log close _all
log using "${log}/log-harp-loanchar`index'", name("log`index'") text replace

*** Indexing
local MaxSample = 2

local DepVarType = ceil(`index'/ `MaxSample')

if `DepVarType' == 1 local DepVar "credit_scorecore_b"
if `DepVarType' == 2 local DepVar "BrokerOrig"
if `DepVarType' == 3 local DepVar "CorrespondentOrig"
if `DepVarType' == 4 local DepVar "int_rate_curr"
if `DepVarType' == 5 local DepVar "debt_to_income_ratio_orig"
if `DepVarType' == 6 local DepVar "loan_to_value_orig"
if `DepVarType' == 7 local DepVar "orig_credit_score"
if `DepVarType' == 8 local DepVar "mi_ins"
if `DepVarType' == 9 local DepVar "oltv"



local index1 = `index' - (`DepVarType' - 1)* `MaxSample'
local SampleType = `index1'

*** Load data
use "${temp}/gse_id-harp-cleaned.dta", clear

do _HARP-sampleselection // sample selection


*keep if inrange(ltvprev, 101, 110)
keep if ltvprev >= 95 & ltvprev <= 115
if `SampleType'==2 {
	su credit_scorecore_b, d
	keep if credit_scorecore_b <= `r(p50)'
}

** additional variables

qui su orig_amount, d
replace orig_amount = . if orig_amount > 417000

gen Cutoff = hi_ltvprev

local Runvar "ltvprev_diff"
global poly1 "Cutoff c.`Runvar' c.`Runvar'#1.Cutoff"
global poly2 "$poly1 c.`Runvar'#c.`Runvar' c.`Runvar'#c.`Runvar'#1.Cutoff"
global poly3 "$poly2 c.`Runvar'#c.`Runvar'#c.`Runvar' c.`Runvar'#c.`Runvar'#c.`Runvar'#1.Cutoff"

*** Regression specification
do _HARP-spec

** Plot

global Poly $poly3
reghdfe `DepVar' $Poly, a(FE1=i.zip_3 FE2=i.seller_id_id FE3=i.orig_ym) vce(robust)
estimate save "${Estimates}/harp-loanchar-DepVar`DepVarType'-Sample`SampleType'", replace

predict resid, r
drop FE* 
foreach x in $Poly {
	replace resid = resid + _b[`x']* (`x')
}

qui su `DepVar' 
replace resid = resid + `r(mean)'

preserve
	qui do "${code}/_labels"
	local title: variable label `DepVar'

	replace ltvprev_diff = ceil(ltvprev_diff* 4)/4
	collapse resid, by(ltvprev_diff)
	
	twoway scatter resid ltvprev_diff, xline(0)  ///
	 saving("${Estimates}/harp-loanchar-DepVar`DepVarType'-Sample`SampleType'.gph", replace) ///
	 title("`title'") ytitle("") xtitle("") ylabel(, angle(0)) graphregion(color(white))
	 
	 
restore

cap log close _all
